import typing
from collections import namedtuple

from PyQt5.QtCore import QAbstractTableModel, QModelIndex, Qt
from PyQt5.QtGui import QColor

WxImage = namedtuple('WxImage', ['file_path', 'extension', 'create_time'])


class TableModel(QAbstractTableModel):
    ROW_INDEX = 0
    FILE_PATH = 1
    EXTENSION = 2
    CREATE_TIME = 3
    COLUMN_COUNT = 4

    def __init__(self):
        super().__init__()

        self.images = [
            WxImage('C:/aa.dat', 'PNG', '2024-01-01 12:00:00'),
            WxImage('C:/bb.dat', 'JPG', '2024-01-01 12:00:00'),
            WxImage('C:/aa.dat', 'PNG', '2024-01-01 12:00:00'),
            WxImage('C:/bb.dat', 'JPG', '2024-01-01 12:00:00'),
            WxImage('C:/aa.dat', 'PNG', '2024-01-01 12:00:00'),
            WxImage('C:/bb.dat', 'JPG', '2024-01-01 12:00:00'),
            WxImage('C:/aa.dat', 'PNG', '2024-01-01 12:00:00'),
            WxImage('C:/bb.dat', 'JPG', '2024-01-01 12:00:00'),
            WxImage('C:/aa.dat', 'PNG', '2024-01-01 12:00:00'),
            WxImage('C:/bb.dat', 'JPG', '2024-01-01 12:00:00'),
            WxImage('C:/aa.dat', 'PNG', '2024-01-01 12:00:00'),
            WxImage('C:/bb.dat', 'JPG', '2024-01-01 12:00:00'),
            WxImage('C:/aa.dat', 'PNG', '2024-01-01 12:00:00'),
            WxImage('C:/bb.dat', 'JPG', '2024-01-01 12:00:00'),
        ]

    def addImages(self, images):
        self.beginResetModel()

        self.images.extend(images)

        self.endResetModel()

    def rowCount(self, parent: QModelIndex = ...) -> int:
        return len(self.images)

    def columnCount(self, parent: QModelIndex = ...) -> int:
        return TableModel.COLUMN_COUNT

    def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...) -> typing.Any:
        if role == Qt.DisplayRole and orientation == Qt.Horizontal:
            return ['Index', 'File', 'Ext', 'Time'][section]

        return None

    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        if role == Qt.DisplayRole:
            image = self.images[index.row()]

            if index.column() == TableModel.ROW_INDEX:
                return index.row() + 1

            elif index.column() == TableModel.FILE_PATH:
                return image.file_path

            elif index.column() == TableModel.EXTENSION:
                return image.extension

            elif index.column() == TableModel.CREATE_TIME:
                return image.create_time

        elif role == Qt.BackgroundRole:
            return QColor.fromHsl((index.row() % 8) * 45, 128, 224)

        return None
